package com.lcm.jnode.controller.api;

import java.util.Date;

import net.dreamlu.api.oauth.OauthQQ;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.jfinal.core.Controller;
import com.lcm.jnode.model.User;
import com.lcm.jnode.model.WBLogin;

/**
 * qq登录api
 * @author L.cm
 * @date 2013-5-14 下午5:08:12
 */
public class QQLogin extends Controller {
	
    private static final Logger log = Logger.getLogger(QQLogin.class);
	
	public void index() {
		try {
			OauthQQ qq = new OauthQQ();
			redirect(qq.getAuthorizeUrl());
		} catch (Exception e) {
			log.error(e.getMessage());
			redirect("/");
		}
	}

	/**
	 * 腾讯回调
	 * @Title: callback
	 * @param     设定文件
	 * @return void    返回类型
	 * @throws
	 * 返回json:<url>http://wiki.connect.qq.com/get_user_info</url>
	 */
	public void callback() {
		try{
			OauthQQ qq = new OauthQQ();
			JSONObject userInfo = qq.getUserInfoByCode(getPara("code"));
			String type = "qq";
			String openid = userInfo.getString("openid");
			String nickname = userInfo.getString("nickname");
			String photoUrl = userInfo.getString("figureurl_2");
			WBLogin login = WBLogin.dao.findByOpenID(openid, type);
			if(null == login) {
	        	login = new WBLogin();
	        	login.set(WBLogin.OPENID, openid).set(WBLogin.TYPE, type).set(WBLogin.HEAD_PHOTO, photoUrl);
				login.set(WBLogin.CREATETIME, new Date()).set(WBLogin.NICKNAME, nickname).save();
	        }
	        if(null == login.getInt(WBLogin.USERID) && null != login.getInt(WBLogin.ID)) {
	        	// 跳转到绑定页
	        	setAttr("id", login.getInt(WBLogin.ID));
	        	setAttr("type", type);
	        	setAttr("nickname", nickname);
	        	setAttr("photourl", photoUrl);
	        	render("binding");
	        	return;
	        }
	        User user = User.dao.findById(login.getInt(WBLogin.USERID));
	    	setSessionAttr("user", user);
		}catch(Exception e){
			log.error(e.getMessage());
		}
		redirect("/admin");
	}
}
